package com.wanggsx.library.util.fun.media.recoder;

import android.media.MediaRecorder;
import android.text.format.DateFormat;
import android.util.Log;

import com.wanggsx.library.util.UtilsFile;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by wanggsx on 15/12/9.
 */
public class VoiceRecoderManger {
    MediaRecorder mr;
    VoiceRecorderListener mListener;
    long startTime = 0;

    public String startRecordVoice(boolean isAutoStop, long stopInMillSeconds, VoiceRecorderListener listener) {
        stopRecordVoice();
        mListener = listener;
        if (isAutoStop && stopInMillSeconds >= 1000) {
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    stopRecordVoice();
                }
            };
            Timer timer = new Timer();
            timer.schedule(task, stopInMillSeconds);
        }
        Log.d("wan", "wanggsx 开始录音");
        return startVoiceRecoding();
    }

    private String startVoiceRecoding() {
        String filePath = UtilsFile.getAutoFileDirectory() + "media/" +
                DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".amr";
        UtilsFile.mkdirs(filePath);
        // 创建录音对象
        mr = new MediaRecorder();
        // 从麦克风源进行录音
        mr.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
        // 设置输出格式
        mr.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
        // 设置编码格式
        mr.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
        mr.setAudioEncodingBitRate(8000);
        // 设置输出文件
        mr.setOutputFile(filePath);
        try {
            // 创建文件
            //file.createNewFile();
            // 准备录制
            mr.prepare();
            // 开始录制
            mr.start();
            startTime = new Date().getTime();
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return filePath;
    }

    public void stopRecordVoice() {
        if (mr != null) {
            try {
                if (mListener != null) {
                    mListener.onFinish(new Date().getTime() - startTime);
                    startTime = 0;
                    mListener = null;
                }
                mr.stop();
                mr.release();
                mr = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
